<script setup lang="ts">
import { computed, ref, onMounted } from 'vue';
import { useAuthStore, useCartStore } from '@/store';
import { storeToRefs } from 'pinia';
import { useRouterPush } from '@/composables';
import { useNurseOrders, useNurseGoods } from '@/service';
import { 
  showToast, 
  showLoading, 
  hideLoading, 
  getCurrentInstance, 
  requestPayment, 
  getStorageSync, 
  setStorageSync, 
  removeStorageSync
} from '@tarojs/taro';
import { SUCCESS_MSG_DURATION } from '@/constants';
import { useDayjs } from '@/hooks/common';
import { useImage } from '@/hooks';
import UserInfo from './components/UserInfo.vue';
import type { CartItem } from '@/store/modules/cart';

const { $dayjs } = useDayjs();
const { addByWeChat } = useNurseOrders();
const { addMedicationOrder } = useNurseGoods();
const { toOrders } = useRouterPush();
const { nurseUser } = storeToRefs(useAuthStore());
const cartStore = useCartStore();

const {
  router: {
    params: { fromCart, fromSingle, orderId }
  }
}: any = getCurrentInstance();

// 动态设置页面标题
const pageTitle = computed(() => {
  return fromSingle === 'true' ? '立即支付' : '订单确认';
});

definePageConfig({
  navigationBarTitleText: '订单确认'
});

// 购物车数据
const cartData = ref<{
  items: CartItem[];
  totalPrice: string;
  totalItems: number;
} | null>(null);

// 表单数据
const formData = ref<any>({
  userId: '',
  familyId: '',
  addrId: '',
  name: '',
  address: '',
  hospital: '',
  defaultHospitalName: '',
  nurseUserOrdersDetails: [],
  beginDate: $dayjs().format('YYYY-MM-DD'),
  endDate: $dayjs().format('YYYY-MM-DD'),
  orderText: ''
});

const loading = ref(false);
const ruleUser = ref();

// 保存删除的商品备份，用于支付失败时恢复
const removedItemsBackup = ref<CartItem[]>([]);

// 恢复购物车商品的通用函数
const restoreCartItems = () => {
  // 只有从购物车过来的商品才需要恢复
  if (fromCart === 'true' && fromSingle !== 'true' && removedItemsBackup.value.length > 0) {
    console.log('恢复购物车商品...');
    
    let restoredCount = 0;
    removedItemsBackup.value.forEach(item => {
      try {
        cartStore.addToCart({
          id: item.id,
          typeName: item.typeName,
          price: item.price,
          pic: item.pic,
          goodsType_dictText: item.goodsType_dictText
        });
        // 设置正确的数量（因为addToCart默认添加1个）
        cartStore.updateItemQuantity(item.id, item.quantity);
        restoredCount++;
        console.log(`已恢复商品到购物车: ${item.typeName} x${item.quantity}`);
      } catch (error) {
        console.error(`恢复商品失败: ${item.typeName}`, error);
      }
    });
    
    console.log(`购物车恢复完成，共恢复 ${restoredCount} 件商品`);
    
    setTimeout(() => {
      showToast({
        title: `已恢复${restoredCount}件商品到购物车`,
        icon: 'none',
        duration: 1500
      });
    }, 1000);
    
    // 清除备份
    removedItemsBackup.value = [];
  } else if (fromSingle === 'true') {
    console.log('单个商品支付失败，无需恢复购物车');
  }
};

// 初始化数据
const initializeData = () => {
  if (fromCart === 'true') {
    const data = getStorageSync('cart_checkout_data');
    if (data && data.items) {
      cartData.value = data;
      
      // 转换购物车数据为订单详情格式
      formData.value.nurseUserOrdersDetails = data.items.map((item: CartItem) => ({
        goodsId: item.id,
        goodsName: item.typeName,
        price: item.price,
        num: item.quantity,
        unit: '个',
        pname: item.goodsType_dictText || '',
        pid: ''
      }));
      
      // 生成订单文本
      if (fromSingle === 'true') {
        // 单个商品的订单文本格式
        formData.value.orderText = `立即购买-${data.items[0].typeName} x${data.items[0].quantity}`;
      } else {
        // 购物车多商品的订单文本格式
        formData.value.orderText = data.items.map((item: CartItem) => 
          `[${item.typeName}] x${item.quantity}`
        ).join(', ');
      }
      
      console.log('初始化数据完成:', {
        来源: fromSingle === 'true' ? '单个商品' : '购物车',
        商品数量: data.items.length,
        订单文本: formData.value.orderText
      });
    }
  }
  
  // 设置用户ID
  if (nurseUser.value?.id) {
    formData.value.userId = nurseUser.value.id;
    formData.value.defaultHospitalName = nurseUser.value.defaultHospitalName || '';
  }
};

// 计算总价
const totalAmount = computed(() => {
  return formData.value.nurseUserOrdersDetails.reduce(
    (sum: number, item: any) => sum + (item.price * item.num),
    0
  );
});

// 检查当前是否在夜班时间，如果是则不允许下单
const checkNightShiftConflict = () => {
  const beginDate = formData.value.beginDate;
  const endDate = formData.value.endDate;
  
  console.log('检查夜班时间冲突:', { beginDate, endDate });
  
  // 夜班时间：18:00 - 次日 08:00
  const nightStartHour = 18; // 18:00
  const nightEndHour = 8;    // 08:00
  
  // 获取当前时间
  const now = new Date();
  const currentHour = now.getHours();
  const today = $dayjs().format('YYYY-MM-DD');
  
  // 主要检查：如果当前时间在夜班时间内，不允许下单
  if (currentHour >= nightStartHour || currentHour < nightEndHour) {
    console.log(`当前时间 ${currentHour}:00 在夜班时间内，不允许下单`);
    return true;
  }
  
  // 次要检查：如果预约的是今天的服务，且当前已接近夜班时间
  if (beginDate === today && currentHour >= nightStartHour - 1) {
    console.log(`当前时间 ${currentHour}:00 接近夜班时间，为确保服务质量暂不接受预约`);
    return true;
  }
  
  // 跨天服务的处理：如果服务跨度超过1天，可能包含夜班时间
  const startDateObj = $dayjs(beginDate);
  const endDateObj = $dayjs(endDate);
  
  if (endDateObj.isAfter(startDateObj)) {
    const daysDiff = endDateObj.diff(startDateObj, 'day');
    if (daysDiff > 1) {
      console.log('多天服务，暂时限制（可能包含夜班时间）');
      return true;
    }
  }
  
  console.log('时间检查通过，允许预约服务');
  return false;
};

// 验证服务时间
const validateServiceTime = () => {
  if (checkNightShiftConflict()) {
    showToast({
      title: '暂不开放夜班服务',
      icon: 'none',
      duration: 2000
    });
    
    // 在控制台显示详细信息
    console.log('夜班服务限制提示:', {
      当前时间: $dayjs().format('YYYY-MM-DD HH:mm:ss'),
      服务开始日期: formData.value.beginDate,
      服务结束日期: formData.value.endDate,
      提示: '服务时间限制在每日 08:00 - 18:00'
    });
    
    return false;
  }
  return true;
};

// 提交订单
const submitOrder = async () => {
  // 验证表单
  const userInfoValid = await ruleUser.value?.validate();
  if (!userInfoValid?.valid) {
    showToast({
      title: '请完善用户信息',
      icon: 'none'
    });
    return;
  }
  
  if (formData.value.nurseUserOrdersDetails.length === 0) {
    showToast({
      title: '购物车为空',
      icon: 'none'
    });
    return;
  }

  if(formData.value.addrId === ''){
    showToast({
      title: '请选择收货地址',
      icon: 'none'
    });
    return;
  }
  
  // 验证服务时间（检查是否在夜班时间）
//   if (!validateServiceTime()) {
//     return;
//   }
  
  // 打印商品列表信息
  console.log('=== 订单确认信息 ===');
  console.log('用户信息:', {
    userId: formData.value.userId,
    name: formData.value.name,
    address: formData.value.address,
    addrId: formData.value.addrId,
    hospital: formData.value.hospital
  });
  console.log('商品列表:', formData.value.nurseUserOrdersDetails);
  console.log('总金额:', totalAmount.value);
  console.log('==================');
  
  // 点击支付时处理购物车商品（只有从购物车过来才需要删除）
  if (fromCart === 'true' && fromSingle !== 'true' && cartData.value) {
    console.log('点击支付，立即从购物车删除商品...');
    
    // 备份要删除的商品，以防支付失败需要恢复
    removedItemsBackup.value = [...cartData.value.items];
    
    // 从购物车中删除商品
    let removedCount = 0;
    cartData.value.items.forEach(item => {
      try {
        cartStore.removeFromCart(item.id);
        removedCount++;
        console.log(`已从购物车移除商品: ${item.typeName} (ID: ${item.id})`);
      } catch (error) {
        console.error(`移除商品失败: ${item.typeName}`, error);
      }
    });
    
    console.log(`购物车清理完成，共移除 ${removedCount} 件商品`);
    
    showToast({
      title: `已从购物车移除${removedCount}件商品`,
      icon: 'success',
      duration: 1000
    });
  } else if (fromSingle === 'true') {
    console.log('单个商品立即支付，无需处理购物车');
  }
  
  loading.value = true;
  showLoading({ title: '正在下单...' });
  
  try {
    // 使用 addMedicationOrder API
    const { error, success } = await addMedicationOrder({
      receive_user: formData.value.userId,
      receive_addr: formData.value.addrId,
      orderText: formData.value.orderText,
      userId: nurseUser.value.id,
      medicationOrderDetails: formData.value.nurseUserOrdersDetails.map((item: any) => ({
        goodsId: item.goodsId,
        num: item.num,
        price: item.price,
      }))
    });
    
    if (!error && success) {
      showToast({
        title: '下单成功',
        icon: 'success',
        duration: SUCCESS_MSG_DURATION
      });
      
      // 调用支付
      await proceedToPay(success);
    } else {
      showToast({
        title: error?.message || '下单失败',
        icon: 'error'
      });
      
      // 下单失败时恢复购物车商品
      restoreCartItems();
    }
  } catch (err) {
    console.error('下单失败:', err);
    showToast({
      title: '下单失败',
      icon: 'error'
    });
    
    // 下单失败时恢复购物车商品
    restoreCartItems();
  } finally {
    hideLoading();
    loading.value = false;
  }
};





// 支付处理
const proceedToPay = async (payInfo: any) => {
  try {
    const { timestamp, noncestr, package: packAge, sign } = payInfo;
    
    await requestPayment({
      timeStamp: timestamp,
      nonceStr: noncestr,
      package: packAge,
      paySign: sign,
      signType: 'RSA',
      success: (res) => {
        if (res.errMsg === 'requestPayment:ok') {
          showToast({
            title: '支付成功！',
            icon: 'success',
            duration: 1500
          });
          
          // 支付成功后清理相关数据
          if (fromCart === 'true') {
            console.log('支付成功，清理相关数据...');
            
            // 清除结算数据
            removeStorageSync('cart_checkout_data');
            
            if (fromSingle === 'true') {
              console.log('单个商品支付成功，无需处理购物车');
            } else {
              // 清除商品备份（购物车商品已删除，支付成功不需要恢复）
              const removedCount = removedItemsBackup.value.length;
              removedItemsBackup.value = [];
              console.log(`购物车支付成功，已购买 ${removedCount} 件商品`);
            }
          }
          
          setTimeout(() => {
            toOrders();
          }, 1500);
        }
      },
      fail: () => {
        showToast({
          title: '支付失败',
          icon: 'error'
        });
        
        // 支付失败时恢复购物车商品
        restoreCartItems();
      }
    });
  } catch (err) {
    console.error('支付失败:', err);
    showToast({
      title: '支付失败',
      icon: 'error'
    });
  }
};

onMounted(() => {
  initializeData();
});
</script>

<template>
  <view class="min-h-screen bg-gray-50">
    <!-- 联系人和地址选择 -->
    <view class="bg-white mb-[20rpx] p-[32rpx]">
      <view class="text-[32rpx] font-bold mb-[24rpx] text-gray-800">收货信息</view>
      <UserInfo 
        :form-data="formData" 
        :nurse-user="nurseUser" 
        ref="ruleUser"
      />
    </view>

    <!-- 商品确认 -->
    <view class="bg-white mb-[20rpx] p-[32rpx]">
      <view class="text-[32rpx] font-bold mb-[24rpx] text-gray-800">
        {{ fromSingle === 'true' ? '商品信息' : '商品确认' }}
      </view>
      
      <view v-if="formData.nurseUserOrdersDetails.length === 0" 
            class="text-center py-[80rpx] text-gray-400">
        <text class="text-[28rpx]">暂无商品</text>
      </view>
      
      <view v-else>
        <view 
          v-for="(item, index) in formData.nurseUserOrdersDetails" 
          :key="index"
          class="flex items-center py-[20rpx] border-b border-gray-100 last:border-0"
        >
          <!-- 商品图片 -->
          <image 
            :src="useImage(cartData?.items[index]?.pic || '')" 
            class="w-[100rpx] h-[100rpx] rounded-[12rpx] bg-gray-200 flex-shrink-0"
          />
          
          <!-- 商品信息 -->
          <view class="flex-1 ml-[20rpx]">
            <view class="text-[26rpx] text-gray-800 font-medium mb-[8rpx]">
              {{ item.goodsName }}
            </view>
            <view v-if="item.pname" class="text-[22rpx] text-gray-500 mb-[8rpx]">
              {{ item.pname }}
            </view>
            <view class="text-[24rpx] text-gray-600">
              数量: {{ item.num }}
            </view>
          </view>
          
          <!-- 价格 -->
          <view class="text-[28rpx] font-bold text-red-500 flex-shrink-0">
            ¥{{ (item.price * item.num).toFixed(2) }}
          </view>
        </view>
      </view>
    </view>

    <!-- 服务时间说明 -->
    <view class="bg-orange-50 mb-[20rpx] p-[32rpx] border-l-[6rpx] border-orange-400">
      <view class="flex items-center mb-[16rpx]">
        <view class="i-mdi-clock-outline text-orange-500 text-[32rpx] mr-[12rpx]"></view>
        <text class="text-[28rpx] font-medium text-orange-600">服务时间说明</text>
      </view>
      <view class="text-[24rpx] text-gray-600 leading-relaxed">
        <view class="mb-[8rpx]">• 接单时间：每日 08:00 - 17:00</view>
        <view class="mb-[8rpx]">• 夜班时间（18:00 - 次日08:00）暂不接受新订单</view>
        <view class="mb-[8rpx]">• 当天17:00后不再接受当日服务预约</view>
        <view class="text-[22rpx] text-gray-500">
          当前时间：{{ $dayjs().format('YYYY-MM-DD HH:mm') }}
        </view>
      </view>
    </view>

    <!-- 总价 -->
    <view class="bg-white mb-[20rpx] p-[32rpx]">
      <view class="flex justify-between items-center">
        <text class="text-[28rpx] text-gray-600">商品总价</text>
        <text class="text-[32rpx] font-bold text-red-500">¥{{ totalAmount.toFixed(2) }}</text>
      </view>
    </view>

    <!-- 底部支付按钮 -->
    <view class="fixed bottom-0 left-0 right-0 bg-white border-t border-gray-200 p-[32rpx] safe-area-bottom">
      <view class="flex items-center justify-between mb-[20rpx]">
        <view class="text-[24rpx] text-gray-500">
          共{{ formData.nurseUserOrdersDetails.reduce((sum: number, item: any) => sum + item.num, 0) }}件商品
        </view>
        <view>
          <text class="text-[24rpx] text-gray-500">总计: </text>
          <text class="text-[32rpx] font-bold text-red-500">¥{{ totalAmount.toFixed(2) }}</text>
        </view>
      </view>
      
      <nut-button 
        type="success" 
        block 
        size="large"
        :loading="loading"
        :disabled="formData.nurseUserOrdersDetails.length === 0"
        @tap="submitOrder"
      >
        {{ loading ? '处理中...' : '立即支付' }}
      </nut-button>
    </view>
    
    <!-- 底部安全区域占位 -->
    <view class="h-[200rpx]"></view>
  </view>
</template>

<style scoped>
.safe-area-bottom {
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);
}
</style>